package com.vcc.web.controller;


import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.SignInException;
import com.vcc.core.util.AesUtil;
import com.vcc.core.util.DateUtil;
import com.vcc.core.util.JwtUtil;
import com.vcc.web.core.component.SseComponent;
import com.vcc.web.core.config.AccountConfig;
import com.vcc.web.core.util.UserUtil;
import com.vcc.service.service.WalletService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Date;

@RestController
@RequestMapping("/sse")
public class SseController {

    @Autowired
    private SseComponent sseComponent;
    @Autowired
    private WalletService walletService;
    @Autowired
    private AccountConfig accountConfig;

    /**
     * 创建SSE长链接
     *
     * @param token  用户token
     * @return org.springframework.web.servlet.mvc.method.annotation.SseEmitter
     * @author re
     * @date 2021/12/12
     **/
    //如果nginx做了跨域处理，此处可去掉
    @RestPack
    @GetMapping("/createSseConnect")
    public SseEmitter createSseConnect(String token, String clientId) {
        Long userId = parseJWT(token);
        return sseComponent.createSseConnect(clientId, userId);
    }

    /**
     * 内部接口
     *
     * @param userId
     * @return
     */
    @RestPack
    @GetMapping("/sendRefreshUsableQuotaMessage")
    public Boolean sendRefreshUsableQuotaMessage(Long userId) {
        sseComponent.sendRefreshUsableQuotaMessage(userId, walletService.listByUserId(userId));
        return true;
    }

    /**
     * 关闭SSE连接
     *
     * @param token  用户token
     * @author re
     * @date 2021/12/13
     **/
    @RestPack
    @GetMapping("/closeSseConnect")
    public Boolean closeSseConnect(String token, String clientId) {
//        Long userId = parseJWT(token);
        Long userId = UserUtil.getId();
        sseComponent.closeSseConnect(clientId, userId);
        return true;
    }

    private Long parseJWT(String token){
        Claims claims = JwtUtil.parseJWT(token, accountConfig.getJwtSecretString());
        Long userId = Long.valueOf(AesUtil.decrypt(claims.get("userId").toString()));
        //过期时间
        Date exp = new Date((Long.parseLong(claims.get("exp").toString())) * 1000);
        //生成时间
        Date nbf = new Date((Long.parseLong(claims.get("nbf").toString())) * 1000);
        if (DateUtil.getDistanceTimestamp(new Date(), exp) < 0) {
            throw new SignInException("用户登录已过期");
        }
        return userId;
    }
}
